package com.li.springbootproject.config.requestlimit.bucket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2022/1/9 12:06
 */
public class TokenLimiter {

    private static final Logger logger = LoggerFactory.getLogger(TokenLimiter.class);

    /**
     * 最后一次令牌发放时间
     */
    public long timeStamp = System.currentTimeMillis();
    /**
     * 桶的容量
     */
    public int capacity = 10;
    /**
     * 令牌生成速度10/s
     */
    public int rate = 10;
    /**
     * 当前令牌数量
     */
    public int tokens;


    public void acquire() throws InterruptedException {
        //  模拟 1000 个请求
        for (int i = 0; i < 1000; i++) {
            long now = System.currentTimeMillis();
            Thread.sleep(4000);
            // 当前令牌数
            tokens = Math.min(capacity, (int) (tokens + (now - timeStamp) * rate / 1000));
            //每隔 0.5 秒发送随机数量的请求
            int permits = (int) (Math.random() * 9) + 1;
            logger.info("请求令牌数：" + permits + "，当前令牌数：" + tokens);
            timeStamp = now;
            if (tokens < permits) {
                // 若不到令牌,则拒绝
                logger.info("限流了");
            } else {
                // 还有令牌，领取令牌
                tokens -= permits;
                logger.info("剩余令牌=" + tokens);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TokenLimiter tokensLimiter = new TokenLimiter();
        tokensLimiter.acquire();
    }

}


